package com.inno.oss.utils;

import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectRequest;
import com.inno.oss.config.OssProperties;
import com.inno.oss.error.OssException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

@Component
@Slf4j
public class OssUtil {
    @Resource
    private OssProperties ossProperties;
    private static final String TEMP_DIR = "temp/oss/";

    public String upload(MultipartFile file) {
        // 创建OSSClient实例。
        OSS ossClient = getOssClient();
        // 将file名和uuid加起来    如果是aaa.xlsx，则最终文件名是uuid_aaa.xlsx
        String originalFilename = file.getOriginalFilename();
        originalFilename = IdUtil.simpleUUID() + "_" + originalFilename;
        // 将文件写入本地项目根目录下临时目录
        String path = saveFile(file, originalFilename);

        try {
            // 创建PutObjectRequest对象。
            File filePath = new File(path);
            PutObjectRequest putObjectRequest = new PutObjectRequest(ossProperties.getBucket(), originalFilename, filePath);

            // 执行上传操作
            ossClient.putObject(putObjectRequest);
            // 生成文件的公开URL // URL有效期1小时
            Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 100);
            URL url = ossClient.generatePresignedUrl(ossProperties.getBucket(), originalFilename, expiration);
            // 获取文件名

            log.info("上传成功 url:{}",url);

            if (filePath.exists()) {
                filePath.delete();
            }
            return url.toString();

            // 关闭OSSClient
        }catch (Exception e) {
            // 日志记录异常信息，根据实际情况处理
            log.error("文件上传失败 ", e);
            throw new OssException("file upload fail !");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

    }
    public OSS getOssClient() {
        return new OSSClientBuilder().build(ossProperties.getEndpoint(), ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret());
    }

    private String saveFile(MultipartFile multipartFile, String fileName){
        File file = new File(TEMP_DIR, fileName);


        File dir = new File(TEMP_DIR);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(multipartFile.getBytes());
        } catch (Exception e) {
            throw new RuntimeException("Failed to save audio file.", e);
        }
        String filePath = TEMP_DIR + fileName;
        return filePath;
    }
    public List<String> uploadBatch(List<MultipartFile> files) {
        // 创建OSSClient实例。
        OSS ossClient = getOssClient();
        List<String> urls = new ArrayList<>();

        for (MultipartFile file : files) {
            try {
                // 将file名和uuid加起来    如果是aaa.xlsx，则最终文件名是uuid_aaa.xlsx
                String originalFilename = file.getOriginalFilename();
                originalFilename = IdUtil.simpleUUID() + "_" + originalFilename;
                // 将文件写入本地项目根目录下临时目录
                String path = saveFile(file, originalFilename);

                // 创建PutObjectRequest对象。
                File filePath = new File(path);
                PutObjectRequest putObjectRequest = new PutObjectRequest(ossProperties.getBucket(), originalFilename, filePath);

                // 执行上传操作
                ossClient.putObject(putObjectRequest);
                // 生成文件的公开URL（如果需要的话）
                Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 100);
                URL url = ossClient.generatePresignedUrl(ossProperties.getBucket(), originalFilename, expiration);
                log.info("上传成功 url:{}", url);

                if (filePath.exists()) {
                    filePath.delete();
                }
                urls.add(url.toString());

            } catch (Exception e) {
                // 日志记录异常信息，根据实际情况处理
                log.error("文件上传失败 ", e);
                throw new OssException("file upload fail !");
            }
        }

        // 关闭OSSClient
        if (ossClient != null) {
            ossClient.shutdown();
        }

        return urls;
    }







}
